<template>
  <a-modal
    :title="modalTitle"
    :width="640"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <a-form-model :model="model" v-bind="formLayout" ref="ruleForm" :rules="rules" @submit.native.prevent>
        <a-form-model-item label="类型" prop="type">
          <a-radio-group v-model="model.type">
            <a-radio :value="1">增加</a-radio>
            <a-radio :value="2">扣除</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="积分" prop="credit">
          <a-input-number size="large" v-model="model.credit" style="width: 200px" />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-input size="large" v-model="model.remark" />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
// 表单字段
const fields = ['id', 'type', 'credit', 'remark']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    model: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      loading: false,
      modalTitle: '改变积分',
      rules: {
        type: [{ required: true, message: '类型必选', trigger: ['blur', 'change'] }],
        credit: [{ required: true, message: '积分必填', trigger: ['blur', 'change'] }]
      },
      form: this.$form.createForm(this)
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))
  },
  mounted() {},
  methods: {
    // 弹出框-确定
    handleOk(e) {
      const { handleFormData } = this
      this.loading = true
      // 验证表单
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          handleFormData('/users/changecredit/' + this.model.id)
        } else {
          const _this = this
          setTimeout(() => {
            _this.loading = false
          }, 600)
        }
      })
    },
    // 弹出框-取消
    handleCancel(e) {
      // 重置表单数据
      this.$refs.ruleForm.resetFields()
      this.$emit('cancel')
    },
    // 表单数据处理
    handleFormData(url) {
      this.$common
        .handlePost(url, this.model)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success(res.message, 1, () => {
              // 重置表单数据
              this.$refs.ruleForm.resetFields()
              // 关闭弹框
              this.$emit('ok')
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.$notification.error({
            message: '错误',
            description: '请求信息失败，请重试'
          })
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>
